package C058;

/**
 * ClassName: c03
 * Package: C058
 * Description:
 *
 * @Author BCXJ
 * @Create 2025/5/3 19:21
 * @Version 1.0
 * @Since 1.0
 */
public class c03 {
    public static void main(String[] args) {
        // int[][] arr = {{1, 0}, {0, 1}};
        //int[][] arr = {{1, 1}, {1, 1}};
        int[][] arr = {{0, 1}, {0, 1}};
        System.out.println(largestIsland(arr));
    }


    public static int largestIsland(int[][] grid) {
        int n = grid.length;
        int m = grid[0].length;
        int id = 2;
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if(grid[i][j] == 1){
                    dfs(i, j, grid, id++);
                }
            }
        }


        // 统计个数
        int[] count = new int[id];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (grid[i][j] > 1) {
                    count[grid[i][j]]++;
                }
            }
        }

        int ans = 0;
        for (int i = 1; i < id; i++) {
            ans = Math.max(count[i - 1], count[i]);
        }
        // 计算答案
        int up, down, left, right, merge;
        boolean[] visited = new boolean[id];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (grid[i][j] == 0) {
                    merge = 0;
                    up = i == 0 ? 0 : grid[i - 1][j];
                    down = i == (n - 1) ? 0 : grid[i + 1][j];
                    left = j == 0 ? 0 : grid[i][j - 1];
                    right = j == (m - 1) ? 0 : grid[i][j + 1];
                    visited[up] = true;
                    merge += count[up];

                    if (!visited[down]) {
                        visited[down] = true;
                        merge += count[down];
                    }

                    if (!visited[left]) {
                        visited[left] = true;
                        merge += count[left];
                    }

                    if (!visited[right]) {
                        visited[right] = true;
                        merge += count[right];
                    }
                    ans = Math.max(ans, merge + 1);
                    visited[up] = false;
                    visited[down] = false;
                    visited[left] = false;
                    visited[right] = false;
                }

            }
        }
        return ans;

    }

    private static void dfs(int i, int j, int[][] grid, int id) {
        if (i == -1 || i == grid.length || j == -1 || j == grid[0].length || grid[i][j] != 1) {
            return;
        }

        grid[i][j] = id;

        dfs(i - 1, j, grid, id);
        dfs(i + 1, j, grid, id);
        dfs(i, j - 1, grid, id);
        dfs(i, j + 1, grid, id);
    }
}
